﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPHelper
{
	public class Service
	{

		public static SPService GetService(SPSite site, string serviceName)
		{
			try
			{
				if (site == null) { site = Site.GetSite(); }
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }

				// get SPFarm
				return GetService(site.WebApplication.Farm, serviceName); 
			}
			catch (Exception ex)
			{
				Log.WriteError("xfcghjvgfydresser", ex);
			}
			return null;
		}

		public static SPService GetService(string serviceName)
		{
			try
			{
				SPSite site = Site.GetSite();
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }

				// get SPFarm
				return GetService(site.WebApplication.Farm, serviceName);
			}
			catch (Exception ex)
			{
				Log.WriteError("6ygfhfgtyyt", ex);
			}
			return null;
		}

		/// <summary>
		/// Get SPService from farm
		/// </summary>
		/// <param name="farm"></param>
		/// <param name="serviceName"></param>
		/// <returns></returns>
		public static SPService GetService(SPFarm farm, string serviceName)
		{
			try
			{
				if (farm == null) { throw new Exception("SPFarm passed is null"); }
				if (string.IsNullOrEmpty(serviceName)) { throw new Exception("No service name passed to look up"); }


				// get SPFarm
				foreach (SPService service in farm.Services)
				{
					if (String.Compare(service.Name, serviceName, true) == 0)
					{
						// found matching service, return
						return service;
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("xfcghjvgfydresser", ex);
			}
			return null;
		}

		/// <summary>
		/// Get all farm level services
		/// </summary>
		/// <param name="farm"></param>
		/// <returns></returns>
		public static List<SPService> GetAllServices(SPFarm farm)
		{
			var services = new List<SPService>();
			try
			{
				if (farm == null) { throw new Exception("SPFarm passed is null"); }


				// get SPFarm
				if (farm.Services != null && farm.Services.Count > 0)
				{
					services.AddRange(farm.Services);
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("xfcghjvgfydresser", ex);
				services = null;
			}
			return services;
		}
	}
}
